<!--
 * @Description: 描述
 * @Author: liym
 * @Date: 2025-05-08 20:14:38
 * @LastEditors: liym
 * @LastEditTime: 2025-06-06 17:16:10
-->
<template>
  <view class="statistics-page">
    <view class="button-search-container">
      <!-- <button @click="showAddModal" size="mini">新增订单</button> -->

      <view class="uni-list">
        <view class="uni-list-cell">
          <!-- <view class="uni-list-cell-left">
            当前选择
          </view> -->
          <view class="uni-list-cell-db">
            <picker
              @change="bindPickerChange"
              range-key="userName"
              :range="agents"
            >
              <input
                class="uni-input"
                readonly
                v-model="searchName"
                placeholder="请选择代理商"
              />
            </picker>
          </view>
          <view
            v-if="searchName"
            class="search-clear"
            @click.stop="handleSearchClear"
            >清空</view
          >
        </view>
      </view>
    </view>
    <view class="table-container">
      <uni-table>
        <uni-tr>
          <uni-th align="center">月份</uni-th>
          <uni-th align="center">总额</uni-th>
          <uni-th align="center">订单数量</uni-th>
        </uni-tr>
        <uni-tr v-for="order in orders" :key="order.id">
          <uni-td align="center">{{ order.month }}</uni-td>
          <uni-td align="center">{{ order.totalAmount }} 元</uni-td>
          <uni-td align="center">{{ order.orderCount }}</uni-td>
        </uni-tr>
      </uni-table>
    </view>
  </view>
</template>

<script>
// import uCharts from '@/components/u-charts/u-charts.js';

import { adminRedirectionMixin } from '@/common/commonMixins.js'
import {
  getOrdersApi,
  getOrdersStatisticsApi,
  updateOrderApi,
  addOrderApi,
  deleteOrderApi,
  getAgentsApi,
} from '@/api'
export default {
  mixins: [adminRedirectionMixin],
  data() {
    return {
      form: {
        month: this.formatDate(new Date(), 'yyyy-MM'),
        agentId: null,
      },
      selectedMonth: this.formatDate(new Date()),
      selectedAgent: null,
      agents: [],
      agentIndex: null,
      orders: [],
      chart: null,
    }
  },
  computed: {
    searchValue() {
      if (this.agentIndex !== null) {
        return this.agents[this.agentIndex].id
      }
      return null
    },
    searchName: {
      get() {
        if (this.agentIndex !== null) {
          return this.agents[this.agentIndex].userName
        }
        return ''
      },
      set(value) {
        console.log('value')
      },
    },
  },
  mounted() {
    this.getAgentList()
    // this.initChart();
    this.getList()
  },
  methods: {
    async fetchStats() {
      const res = await uni.request({
        url: '/admin/statistics',
        data: {
          month: this.selectedMonth,
          agentId: this.selectedAgent,
        },
      })
      this.updateChart(res.data)
    },
    handleSearchClear() {
      console.log('ddddd')
      this.agentIndex = null

      this.$nextTick(() => {
        this.getList()
      })
    },
    async handleSearch() {
      try {
        uni.showLoading({
          title: 'loading',
          mask: true,
        })

        uni.hideLoading()
        this.getList()
      } catch {
        uni.hideLoading()
      }
    },
    async getList() {
      try {
        uni.showLoading({
          title: 'loading',
          mask: true,
        })

        const res = await getOrdersStatisticsApi({
      
          agentId: this.searchValue
        })
        console.log('res :>> ', res)
        this.orders = res.data
        uni.hideLoading()
      } catch {
        uni.hideLoading()
      }
    },
    async getAgentList() {
      uni.showLoading({
        title: 'loading',
        mask: true,
      })
      try {
        const { data } = await getAgentsApi({
          currentPage: 1,
          pageSize: 99999,
        })

        this.agents = data.records || []
      } finally {
        uni.hideLoading()
      }
    },
    bindPickerChange(event) {
      console.log(event.detail.value)
      this.agentIndex = event.detail.value

      this.$nextTick(() => {
        this.getList()
      })
    },
    initChart() {
      this.chart = new uCharts({
        canvasId: 'myChart',
        type: 'column',
        dataLabel: true,
      })
    },
    formatDate(date, format = 'yyyy-MM') {
      if (!(date instanceof Date)) {
        date = new Date(date) // 支持时间戳或字符串
      }

      const pad = (n) => n.toString().padStart(2, '0')

      const map = {
        yyyy: date.getFullYear(),
        MM: pad(date.getMonth() + 1),
        dd: pad(date.getDate()),
        HH: pad(date.getHours()),
        mm: pad(date.getMinutes()),
        ss: pad(date.getSeconds()),
      }

      return format.replace(/yyyy|MM|dd|HH|mm|ss/g, (match) => map[match])
    },
    updateChart(data) {
      this.chart.updateData({
        categories: data.map((item) => item.month),
        series: [
          {
            data: data.map((item) => ({ value: item.totalAmount })),
          },
        ],
      })
    },
    bindDateChange(e) {
      console.log(e, e.detail.value)
      this.form.month = e.detail.value
    },
  },
}
</script>

<style scoped lang="scss">
.uni-list-cell-left {
  width: 100rpx;
}
.search-footer {
  margin-top: 10rpx;
  padding: 20rpx;
}
.search-button {
}

.search-clear {
  padding: 0 10px;
  color: #2979ff;
}

.button-search-container {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 10px;
  .uni-list {
    flex: 1;
    min-width: 0;
  }
}

.button-search-container button {
  min-width: 0;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  margin-right: 10px;
  margin-bottom: 0;
  flex-basis: auto;
  flex-grow: 0;
  flex-shrink: 1;
  height: auto;
  padding: 5px 10px;
}

uni-search-bar {
  flex: 1;
}
</style>
